﻿//https://leetcode.cn/problems/3sum/

//我的
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int fix = 0, left = 1, right = nums.size() - 1;
        vector<vector<int>> ret;
        sort(nums.begin(), nums.end());

        for (; fix < nums.size() - 2; ++fix)
        {
            //cout<<"fix:"<<fix<<" "<<endl;
            if (fix != 0 && nums[fix] == nums[fix - 1])continue;

            left = fix + 1;
            right = nums.size() - 1;
            while (left < right)
            {
                //cout<<"left:"<<left<<" | "<<"right:"<<right<<endl;
                if (nums[left] + nums[right] < -1 * nums[fix])left++;
                else if (nums[left] + nums[right] > -1 * nums[fix])right--;
                else
                {
                    if (left > fix + 1 && nums[left] == nums[left - 1])
                    {
                        left++;
                        continue;
                    }
                    if (right < nums.size() - 1 && nums[right] == nums[right + 1])
                    {
                        right--;
                        continue;
                    }

                    vector<int> tmp = { nums[fix],nums[left],nums[right] };
                    ret.push_back(tmp);
                    left++; right--;
                    cout << " push:" << nums[fix] << nums[left] << nums[right] << " ";
                }
            }
            cout << endl;
        }
        return ret;
    }
};

//答案
class Solution
{
public:
    vector<vector<int>> threeSum(vector<int>& nums)
    {
        vector<vector<int>> ret;
        // 1. 排序
        sort(nums.begin(), nums.end());
        // 2. 利⽤双指针解决问题
        int n = nums.size();
        for (int i = 0; i < n; ) // 固定数 a
        {
            if (nums[i] > 0) break; // ⼩优化
            int left = i + 1, right = n - 1, target = -nums[i];
            while (left < right)
            {
                int sum = nums[left] + nums[right];
                if (sum > target) right--;
                else if (sum < target) left++;
                else
                {
                    ret.push_back({ nums[i], nums[left], nums[right] });
                    left++, right--;
                    // 去重操作 left 和 right
                    while (left < right && nums[left] == nums[left - 1]) left++;
                    while (left < right && nums[right] == nums[right + 1])
                        right--;
                }
            }
            // 去重 i
            i++;
            while (i < n && nums[i] == nums[i - 1]) i++;
        }
        return ret;
    }
};